package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.springboot.common.Result;
import org.example.springboot.entity.Logistics;
import org.example.springboot.entity.Order;
import org.example.springboot.entity.Product;
import org.example.springboot.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class LogisticsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogisticsService.class);

    @Autowired
    private LogisticsMapper logisticsMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private ProductMapper productMapper;

    public Result<?> createLogistics(Logistics logistics) {
        try {
            // 检查订单是否存在
            Order order = orderMapper.selectById(logistics.getOrderId());
            if (order == null) {
                return Result.error("-1", "订单不存在");
            }

            // 检查订单状态是否为已支付
            if (order.getStatus() != 1) {
                return Result.error("-1", "订单状态不正确，只能为已支付订单创建物流");
            }

            // 检查必填字段
            if (logistics.getCompanyName() == null || logistics.getCompanyName().trim().isEmpty()) {
                return Result.error("-1", "物流公司名称不能为空");
            }
            if (logistics.getTrackingNumber() == null || logistics.getTrackingNumber().trim().isEmpty()) {
                return Result.error("-1", "物流单号不能为空");
            }
            
            // 设置物流状态为已发货
            logistics.setStatus(1); // 1表示已发货
            
            // 设置最后更新时间
            Timestamp now = Timestamp.valueOf(LocalDateTime.now());
            logistics.setLastUpdateTime(now);

            int result = logisticsMapper.insert(logistics);
            if (result > 0) {
                // 更新订单状态为已发货
                order.setStatus(2); // 2表示已发货
                order.setDeliveryTime(now); // 设置发货时间
                orderMapper.updateById(order);
                
                LOGGER.info("创建物流信息成功，物流ID：{}", logistics.getId());
                return Result.success(logistics);
            }
            return Result.error("-1", "创建物流信息失败");
        } catch (Exception e) {
            LOGGER.error("创建物流信息失败：{}", e.getMessage());
            return Result.error("-1", "创建物流信息失败：" + e.getMessage());
        }
    }

    public Result<?> updateLogisticsStatus(Long id, Integer status) {
        try {
            Logistics logistics = logisticsMapper.selectById(id);
            if (logistics == null) {
                return Result.error("-1", "未找到物流信息");
            }

            logistics.setStatus(status);
            logistics.setLastUpdateTime(Timestamp.valueOf(LocalDateTime.now())); // 更新最后更新时间
            
            int result = logisticsMapper.updateById(logistics);
            if (result > 0) {
                // 根据物流状态更新订单状态
                Order order = orderMapper.selectById(logistics.getOrderId());
                if (order != null) {
                    Timestamp now = Timestamp.valueOf(LocalDateTime.now());
                    switch (status) {
                        case 1: // 已发货
                            order.setStatus(2); // 已发货
                            order.setDeliveryTime(now);
                            break;
                        case 3: // 已签收
                            order.setStatus(3); // 已完成
                            order.setCompleteTime(now);
                            break;
                        case 4: // 异常
                            // 可以根据业务需求决定是否更新订单状态
                            break;
                        case 5: // 已退款
                            order.setStatus(6); // 已退款
                            break;
                    }
                    orderMapper.updateById(order);
                }

                LOGGER.info("更新物流状态成功，物流ID：{}，新状态：{}", id, status);
                return Result.success(logistics);
            }
            return Result.error("-1", "更新物流状态失败");
        } catch (Exception e) {
            LOGGER.error("更新物流状态失败：{}", e.getMessage());
            return Result.error("-1", "更新物流状态失败：" + e.getMessage());
        }
    }

    public Result<?> deleteLogistics(Long id) {
        try {
            Logistics logistics = logisticsMapper.selectById(id);
            if (logistics == null) {
                return Result.error("-1", "未找到物流信息");
            }

            // 检查物流状态，只有异常的物流信息才能删除
            if (logistics.getStatus() != 4) {
                return Result.error("-1", "当前物流状态不允许删除");
            }

            int result = logisticsMapper.deleteById(id);
            if (result > 0) {
                LOGGER.info("删除物流信息成功，物流ID：{}", id);
                return Result.success();
            }
            return Result.error("-1", "删除物流信息失败");
        } catch (Exception e) {
            LOGGER.error("删除物流信息失败：{}", e.getMessage());
            return Result.error("-1", "删除物流信息失败：" + e.getMessage());
        }
    }

    public Result<?> getLogisticsById(Long id) {
        Logistics logistics = logisticsMapper.selectById(id);
        if (logistics != null) {
            // 填充关联信息
            logistics.setOrder(orderMapper.selectById(logistics.getOrderId()));

            return Result.success(logistics);
        }
        return Result.error("-1", "未找到物流信息");
    }

    public Result<?> getLogisticsByOrderId(Long orderId) {
        LambdaQueryWrapper<Logistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Logistics::getOrderId, orderId);
        Logistics logistics = logisticsMapper.selectOne(queryWrapper);
        if (logistics != null) {
            // 填充关联信息
            logistics.setOrder(orderMapper.selectById(logistics.getOrderId()));

            return Result.success(logistics);
        }
        return Result.error("-1", "未找到物流信息");
    }

    public Result<?> getLogisticsByPage(Long orderId, Long merchantId, Integer status, Integer currentPage, Integer size) {
        try {
            // 创建分页对象
            Page<Logistics> page = new Page<>(currentPage, size);
            
            // 创建查询构造器
            LambdaQueryWrapper<Logistics> queryWrapper = new LambdaQueryWrapper<>();
            
            // 基础条件
            queryWrapper.eq(orderId != null, Logistics::getOrderId, orderId);
            queryWrapper.eq(status != null, Logistics::getStatus, status);
            
            if (merchantId != null) {
                // 先查询该商户的所有商品ID
                LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
                productWrapper.eq(Product::getMerchantId, merchantId);
                List<Product> products = productMapper.selectList(productWrapper);
                List<Long> productIds = products.stream().map(Product::getId).collect(Collectors.toList());
                
                if (!productIds.isEmpty()) {
                    // 查询包含这些商品的订单ID
                    LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
                    orderWrapper.in(Order::getProductId, productIds);
                    List<Order> orders = orderMapper.selectList(orderWrapper);
                    List<Long> orderIds = orders.stream().map(Order::getId).collect(Collectors.toList());
                    
                    if (!orderIds.isEmpty()) {
                        queryWrapper.in(Logistics::getOrderId, orderIds);
                    } else {
                        // 如果没有找到相关订单，直接返回空结果
                        return Result.success(new Page<>());
                    }
                } else {
                    // 如果没有找到该商户的商品，直接返回空结果
                    return Result.success(new Page<>());
                }
            }

            // 按创建时间倒序排序
            queryWrapper.orderByDesc(Logistics::getCreatedAt);

            // 执行分页查询
            Page<Logistics> result = logisticsMapper.selectPage(page, queryWrapper);

            // 填充关联信息
            result.getRecords().forEach(logistics -> {
                Order order = orderMapper.selectById(logistics.getOrderId());
                if (order != null) {
                    logistics.setOrder(order);
                    // 可以选择性地填充产品信息
                    order.setProduct(productMapper.selectById(order.getProductId()));
                }
            });

            LOGGER.info("分页查询物流信息成功，当前页：{}，每页大小：{}", currentPage, size);
            return Result.success(result);
        } catch (Exception e) {
            LOGGER.error("分页查询物流信息失败：{}", e.getMessage());
            return Result.error("-1", "分页查询物流信息失败：" + e.getMessage());
        }
    }

    public Result<?> deleteBatch(List<Long> ids) {
        try {
            // 检查每个物流信息的状态
            for (Long id : ids) {
                Logistics logistics = logisticsMapper.selectById(id);
                if (logistics != null && logistics.getStatus() != 4) {
                    return Result.error("-1", "物流ID：" + id + " 当前状态不允许删除");
                }
            }

            int result = logisticsMapper.deleteBatchIds(ids);
            if (result > 0) {
                LOGGER.info("批量删除物流信息成功，删除数量：{}", result);
                return Result.success();
            }
            return Result.error("-1", "批量删除物流信息失败");
        } catch (Exception e) {
            LOGGER.error("批量删除物流信息失败：{}", e.getMessage());
            return Result.error("-1", "批量删除物流信息失败：" + e.getMessage());
        }
    }

    public Result<?> signLogistics(Long id) {
        try {
            Logistics logistics = logisticsMapper.selectById(id);
            if (logistics == null) {
                return Result.error("-1", "未找到物流信息");
            }

            // 检查当前状态是否为已发货或运输中
            if (logistics.getStatus() != 1 && logistics.getStatus() != 2) {
                return Result.error("-1", "当前物流状态不允许签收");
            }

            // 更新物流状态为已签收
            logistics.setStatus(3); // 3表示已签收
            logistics.setLastUpdateTime(Timestamp.valueOf(LocalDateTime.now())); // 更新最后更新时间
            int result = logisticsMapper.updateById(logistics);
            
            if (result > 0) {
                // 更新订单状态为已完成
                Order order = orderMapper.selectById(logistics.getOrderId());
                if (order != null) {
                    order.setStatus(3); // 3表示已完成
                    order.setCompleteTime(Timestamp.valueOf(LocalDateTime.now())); // 设置完成时间
                    orderMapper.updateById(order);
                }

                LOGGER.info("物流签收成功，物流ID：{}", id);
                return Result.success(logistics);
            }
            return Result.error("-1", "物流签收失败");
        } catch (Exception e) {
            LOGGER.error("物流签收失败：{}", e.getMessage());
            return Result.error("-1", "物流签收失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取物流统计数据
     * @param merchantId 商户ID (可选)
     * @return 物流统计数据
     */
    public Map<String, Object> getLogisticsStatistics(Long merchantId) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 构建基础查询条件
            LambdaQueryWrapper<Logistics> baseQuery = new LambdaQueryWrapper<>();
            
            if (merchantId != null) {
                // 如果指定了商户ID，则查询该商户的商品相关订单的物流
                List<Product> products = productMapper.selectList(
                    new LambdaQueryWrapper<Product>().eq(Product::getMerchantId, merchantId)
                );
                
                if (products.isEmpty()) {
                    // 如果商户没有商品，则返回空统计
                    statistics.put("totalCount", 0);
                    statistics.put("shippedCount", 0);      // 已发货
                    statistics.put("inTransitCount", 0);    // 运输中
                    statistics.put("deliveredCount", 0);    // 已签收
                    statistics.put("exceptionCount", 0);    // 异常
                    statistics.put("refundedCount", 0);     // 已退款
                    statistics.put("todayShippedCount", 0); // 今日发货
                    statistics.put("weekShippedCount", 0);  // 本周发货
                    statistics.put("onTimeRate", 0);        // 准时率
                    statistics.put("signRate", 0);          // 签收率
                    statistics.put("avgDeliveryDays", 0);   // 平均送达天数
                    return statistics;
                }
                
                List<Long> productIds = products.stream().map(Product::getId).collect(Collectors.toList());
                
                // 查询包含这些商品的订单ID
                LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
                orderWrapper.in(Order::getProductId, productIds);
                List<Order> orders = orderMapper.selectList(orderWrapper);
                
                if (orders.isEmpty()) {
                    // 如果没有订单，则返回空统计
                    statistics.put("totalCount", 0);
                    statistics.put("shippedCount", 0);
                    statistics.put("inTransitCount", 0);
                    statistics.put("deliveredCount", 0);
                    statistics.put("exceptionCount", 0);
                    statistics.put("refundedCount", 0);
                    statistics.put("todayShippedCount", 0);
                    statistics.put("weekShippedCount", 0);
                    statistics.put("onTimeRate", 0);
                    statistics.put("signRate", 0);
                    statistics.put("avgDeliveryDays", 0);
                    return statistics;
                }
                
                List<Long> orderIds = orders.stream().map(Order::getId).collect(Collectors.toList());
                baseQuery.in(Logistics::getOrderId, orderIds);
            }
            
            // 查询所有物流记录
            List<Logistics> allLogistics = logisticsMapper.selectList(baseQuery);
            
            // 计算总物流数
            int totalCount = allLogistics.size();
            
            // 按状态统计物流数量
            int shippedCount = 0;    // 已发货(状态1)
            int inTransitCount = 0;  // 运输中(状态2)
            int deliveredCount = 0;  // 已签收(状态3)
            int exceptionCount = 0;  // 异常(状态4)
            int refundedCount = 0;   // 已退款(状态5)
            
            // 时间相关统计
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime todayStart = now.toLocalDate().atStartOfDay();
            LocalDateTime weekStart = now.minusDays(now.getDayOfWeek().getValue() - 1).toLocalDate().atStartOfDay();
            
            int todayShippedCount = 0;
            int weekShippedCount = 0;
            
            // 计算准时送达和平均送达天数
            int onTimeDeliveryCount = 0;
            int totalDeliveryDays = 0;
            int deliveryOrderCount = 0;
            
            for (Logistics logistics : allLogistics) {
                // 按状态统计
                if (logistics.getStatus() != null) {
                    switch (logistics.getStatus()) {
                        case 1: shippedCount++; break;
                        case 2: inTransitCount++; break;
                        case 3: deliveredCount++; break;
                        case 4: exceptionCount++; break;
                        case 5: refundedCount++; break;
                    }
                }
                
                // 时间相关统计
                if (logistics.getCreatedAt() != null) {
                    LocalDateTime createdAt = logistics.getCreatedAt().toLocalDateTime();
                    
                    // 今日发货
                    if (createdAt.isAfter(todayStart) || createdAt.isEqual(todayStart)) {
                        todayShippedCount++;
                    }
                    
                    // 本周发货
                    if (createdAt.isAfter(weekStart) || createdAt.isEqual(weekStart)) {
                        weekShippedCount++;
                    }
                }
                
                // 准时率和平均送达天数计算
                if (logistics.getStatus() == 3 && logistics.getExpectedArrivalTime() != null && logistics.getLastUpdateTime() != null) {
                    deliveryOrderCount++;
                    
                    // 判断是否准时送达
                    if (logistics.getLastUpdateTime().toLocalDateTime().isBefore(logistics.getExpectedArrivalTime().toLocalDateTime()) || 
                        logistics.getLastUpdateTime().toLocalDateTime().isEqual(logistics.getExpectedArrivalTime().toLocalDateTime())) {
                        onTimeDeliveryCount++;
                    }
                    
                    // 计算送达天数
                    if (logistics.getCreatedAt() != null) {
                        long days = java.time.Duration.between(
                            logistics.getCreatedAt().toLocalDateTime(),
                            logistics.getLastUpdateTime().toLocalDateTime()
                        ).toDays();
                        totalDeliveryDays += days;
                    }
                }
            }
            
            // 计算准时率
            double onTimeRate = deliveryOrderCount > 0 ? (double) onTimeDeliveryCount / deliveryOrderCount * 100 : 0;
            
            // 计算签收率
            double signRate = totalCount > 0 ? (double) deliveredCount / totalCount * 100 : 0;
            
            // 计算平均送达天数
            double avgDeliveryDays = deliveryOrderCount > 0 ? (double) totalDeliveryDays / deliveryOrderCount : 0;
            
            // 整合统计结果
            statistics.put("totalCount", totalCount);
            statistics.put("shippedCount", shippedCount);
            statistics.put("inTransitCount", inTransitCount);
            statistics.put("deliveredCount", deliveredCount);
            statistics.put("exceptionCount", exceptionCount);
            statistics.put("refundedCount", refundedCount);
            statistics.put("todayShippedCount", todayShippedCount);
            statistics.put("weekShippedCount", weekShippedCount);
            statistics.put("onTimeRate", Math.round(onTimeRate * 100) / 100.0); // 保留两位小数
            statistics.put("signRate", Math.round(signRate * 100) / 100.0);     // 保留两位小数
            statistics.put("avgDeliveryDays", Math.round(avgDeliveryDays * 10) / 10.0); // 保留一位小数
            
            return statistics;
        } catch (Exception e) {
            LOGGER.error("获取物流统计数据失败：{}", e.getMessage());
            Map<String, Object> errorStats = new HashMap<>();
            errorStats.put("error", "获取物流统计数据失败");
            return errorStats;
        }
    }
} 